var initialareamsg="Please Select City First",
initialSelectedStateMsg="All Cities Selected",
initialSelectedLocationMsg="All Location Selected",
initialSelectedSubAreaMsg="All Sub Area Selected";
$(document).ready(function() {
	if(browser == "Internet Explorer") {
		if(version <= 8) {
			browserPopup.init();
		}
	}
	freetextAction.init();
	homloan_scrollToCalculator.init();
	addYourProperty.init();
	memberRegistration.init();
	scrollToTop.init();
	//scrollToHome.init();
	contactUs.init();
	projectDirectoryTabs.init();
	$('#main-slider').flexslider();
	
    /* Search */
    $('#search-by-map').bind('click', function() {
        url = siteurl + 'listing-map.html?';
		
        var keyword = $('input[name=\'keyword\']').attr('value');
        var propertyfor = $('input:radio[name=propertyfor]:checked').val();
        var localorint = $('input:radio[name=localorint]:checked').val();
        var cities =  $('select[name="locations"]').val();
        var ddlPropertyType = $('select[name="ddlPropertyType"]').val();
        var propertytype = $('select[name="propertytype"]').val();
		
        if(localorint) {
        	url += 'localorint=' + encodeURIComponent(localorint);
        }
        
        if(propertyfor) {
        	url += '&propertyfor=' + encodeURIComponent(propertyfor);
        }
        
        if (keyword) {
            url += '&keyword=' + encodeURIComponent(keyword);
        }
        
        if(cities) {
        	url += '&locations=' + encodeURIComponent(cities);
        }
        
        if(propertytype) {
        	url += '&propertytype=' + encodeURIComponent(propertytype);
        }
		
        location = url;
    });
   
    //
    $('input:radio[name=\'localorint\']').bind('change', function() {
    	var localorint = $('input:radio[name=localorint]:checked').val();
    	
    	if(localorint == 0) {
    		$.ajax({
				url: 'member/getDistricts?location=' + localorint,
				dataType: 'json',
				beforeSend: function() {
					$('select[name=\'locations\']').after('<span class="wait">&nbsp;<img src="'+ siteurl +'assets/img/loading.gif" alt="" /></span>');
				},
				complete: function() {
					$('.wait').remove();
				},			
				success: function(json) {
					var ddlPropertyType = getURLVar('locations');
					html = '<option value="">'+ text_district +'</option>';
					
					if (json.length > 0) {
						for (i = 0; i < json.length; i++) {
							
		        			html += '<option value="' + json[i]['Location_ID'] + '"';
	
		        			if(ddlPropertyType != '' && ddlPropertyType == json[i]['Location_ID']) {
								html += 'selected="selected"';
			        		}
			    			
							html += '>' + json[i]['Name'] + '</option>';
						}
					}
					
					$name = $('#inputLocation').text();
					if($name != "") {
						$('#inputLocation').text("All Districts");
					}
					
					$('#inputCity').text('District');
					
					$('#inputLocation').attr('name', 'locations');
					
					//set city name attribute to default value
					$('input[name=\'cities\']').val(cityVal);
					
					$('select[name=\'locations\']').html(html);
				},
				error: function(xhr, ajaxOptions, thrownError) {
					alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
				}
			});
    	} else {
			$.ajax({
				url: 'member/getInternationalCountries?location=' + localorint,
				dataType: 'json',
				beforeSend: function() {
					$('select[name=\'locations\']').after('<span class="wait">&nbsp;<img src="'+ siteurl +'assets/img/loading.gif" alt="" /></span>');
				},
				complete: function() {
					$('.wait').remove();
				},			
				success: function(json) {
					var ddlPropertyType = getURLVar('country');
					html = '<option value="">'+ text_all_countries +'</option>';
					
					if (json.length > 0) {
						for (i = 0; i < json.length; i++) {
							
		        			html += '<option value="' + json[i]['Country_ID'] + '"';
	
		        			if(ddlPropertyType != '' && ddlPropertyType == json[i]['Country_ID']) {
								html += 'selected="selected"';
			        		}
			    			
							html += '>' + json[i]['Name'] + '</option>';
						}
					}
					
					$name = $('#inputLocation').text();
					if($name != "") {
						$('#inputLocation').text("Country");
					}
					
					$('#inputCity').text('Country');
					
					$('#inputLocation').attr('name', 'country');
					
					//Reset the cities value
					$('input[name=\'cities\']').val("");
					
					$('select[name=\'country\']').html(html);
				},
				error: function(xhr, ajaxOptions, thrownError) {
					alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
				}
			});
    	}
	});
    
    $('input:radio[name=\'localorint\']').trigger('change');
    
    //currency convertor
    $(".curencyid_ajax").change(function(){
    	var price  = $(this).parent().parent().children('.price_usd').text();
        var unit_price  = $(this).parent().parent().children('.unit_price').text();
        price = $.trim(price);
        var currency = $(this).val().replace(" ","");
        var page_url  = siteurl + "listingrows/quick_convert_price/"+price+"/"+currency;
        var obj = $(this).parent().parent();
        var tS=new Date().getTime();
        var detailHref = "";
        var trainindIdArray = new Array;
        if(currency == unit_price) {
            var data = obj.children('.asking_price_local_int').text();
            obj.children('.spanusd').text("Estimated "+" "+data);
            $('.spanusd').show();
        } else {
	    	$.ajax({
	            url  : page_url ,
	            data: {timestamp:tS},
	            cache: true,
	            type : "POST",
	            success : function(data) {
	                var obj_curr = data.substr(0, 3);
	                
	                //obj.children('.price').text("Price:"+" "+data);
	                //obj.children('.price_rate').text("Rate:"+" "+obj_curr + " " + number_format(obj_rate));
	                obj.children('.spanusd').text("Estimated "+currency+" "+data);
	                $('.spanusd').show();
	            }
	        });
        }
    });
    
    $('.contact_agent').bind('click',function(){
    	var listing_ID  = $(this).parent().children('#morelinks').val();
    	
    	var url = siteurl + 'detail/' + listing_ID + '#contactAgent';
    	location = url;
    });
    
    $('.view_detail').bind('click',function(){
    	/*
    	 * Author: Chi Nguyen
    	 * get listing id based on value that is being set inside hiden input
    	 */
    	var listing_ID  = $(this).parent().children('#morelinks').val();
    	
    	var url = siteurl + 'detail/' + listing_ID;
    	location = url;
    });
    
    $('.short_list').bind('click',function(){
    	var listing_ID  = $(this).parent().children('#morelinks').val();
        $(this).html('Shortlisted').addClass('disabled');
    	addToWishList(listing_ID);
    });
    
    $('.save-short-list').bind('click',function(){
    	var url = siteurl + 'shortlist/save';
    	location = url;
    });
    
    //View Find An Expert Detail
    $('.find_an_expert_btn').bind('click',function(){
    	/*
    	 * Author: Chi Nguyen
    	 * get user id based on value that is being set inside hiden input
    	 */
    	//var User_ID  = $(this).parent().children('#findanexpert').val();
    	
    	//var url = siteurl + 'find-an-expert/detail/' + User_ID;
    	//location = url;
    });
	
    $('#header input[name=\'filter_name\']').bind('keydown', function(e) {
        if (e.keyCode == 13) {
            url = $('base').attr('href') + 'index.php?route=product/search';
			 
            var filter_name = $('input[name=\'filter_name\']').attr('value');
			
            if (filter_name) {
                url += '&filter_name=' + encodeURIComponent(filter_name);
            }
			
            location = url;
        }
    });

    $(document).on("click", ".success img, .warning img, .attention img, .information img", function(){
        $(this).parent().fadeOut('slow', function() {
            $(this).remove();
        });
    });
});

//show popup
browserPopup = {
	init: function() {
		$(".message").fancybox({
			maxWidth	: 600,
			minHeight	: 100,
			maxHeight	: 200,
			afterLoad	: function () { $("#content, #page").fadeOut(100); },
			afterClose	: function () { $("#content, #page").fadeIn(10); },
			width		: '50%',
			height		: '90%',
			closeClick	: false,
			openEffect	: 'fade',
			closeEffect	: 'fade',
			padding		: '0',
			modal		: false,
			hideLoading	: true,
			title		: false,
			nextClick	: false,
			type		: 'iframe',
			helpers 	: { title : { type : 'over'} },
			href: siteurl + 'portal/message'
		});
		
		$(".message").trigger("click");
	}
};

//get url
function getURLVar(key) {
	var value = [];
	var query = String(document.location).split('?');
	
	if (query[1]) {
		var part = query[1].split('&');

		for (i = 0; i < part.length; i++) {
			var data = part[i].split('=');
			
			if (data[0] && data[1]) {
				value[data[0]] = data[1];
			}
		}
		
		if (value[key]) {
			return value[key];
		} else {
			return '';
		}
	}
}

projectDirectoryTabs = {
    init: function() {
		$('#tabs a').tabs();
    }
};

freetextAction = {
		init: function() {
			$('.keyword').focus(function(){
		        if($(this).val() == 'Enter keyword of Properties') {
		            $(this).val('');
		        }
		    });
		            
		    $('.keyword').blur(function(){
		        if($(this).val() == '') {
		            $(this).val('Enter keyword of Properties');
		        }
		    });
		    
		    $('.price_min').focus(function(){
	            if($(this).val() == 'Min') {
	                $(this).val('');
	            }
	        });

	        $('.price_min').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Min');
	            }
	        });
		    
		    $('.price_max').focus(function(){
	            if($(this).val() == 'Max') {
	                $(this).val('');
	            }
	        });

	        $('.price_max').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Max');
	            }
	        });
	        
	        $('.size_min').focus(function(){
	            if($(this).val() == 'Min') {
	                $(this).val('');
	            }
	        });

	        $('.size_min').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Min');
	            }
	        });
		    
		    $('.size_max').focus(function(){
	            if($(this).val() == 'Max') {
	                $(this).val('');
	            }
	        });

	        $('.size_max').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Max');
	            }
	        });
	        
	        $('.bed_min').focus(function(){
	            if($(this).val() == 'Min') {
	                $(this).val('');
	            }
	        });

	        $('.bed_min').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Min');
	            }
	        });
	        
	        $('.bed_max').focus(function(){
	            if($(this).val() == 'Max') {
	                $(this).val('');
	            }
	        });

	        $('.bed_max').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Max');
	            }
	        });
	        
	        $('.bath_min').focus(function(){
	            if($(this).val() == 'Min') {
	                $(this).val('');
	            }
	        });

	        $('.bath_min').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Min');
	            }
	        });
	        
	        $('.bath_max').focus(function(){
	            if($(this).val() == 'Max') {
	                $(this).val('');
	            }
	        });

	        $('.bath_max').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Max');
	            }
	        });
	        
	        $('.member_firstname').focus(function(){
	            if($(this).val() == 'First Name') {
	                $(this).val('');
	            }
	        });

	        $('.member_firstname').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('First Name');
	            }
	        });
	        
	        $('.member_lastname').focus(function(){
	            if($(this).val() == 'Last Name') {
	                $(this).val('');
	            }
	        });

	        $('.member_lastname').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Last Name');
	            }
	        });
	        
	        $('.member_emailaddress').focus(function(){
	            if($(this).val() == 'Email Address') {
	                $(this).val('');
	            }
	        });

	        $('.member_emailaddress').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Email Address');
	            }
	        });
	        
	        $('.member_password').focus(function(){
	        	
	        	var password = $('input[name=\'password\']').attr('value');
	        	
	            if(password == 'Password') {
	            	$(this).val('');
	            }
	        });

	        $('.member_password').blur(function(){
	        	var password = $('input[name=\'password\']').attr('value');
	            if(password == '') {
	            	$(this).val('Password');
	            }
	        });
	        
	        $('.agent_name').focus(function(){
	            if($(this).val() == 'Name') {
	                $(this).val('');
	            }
	        });

	        $('.agent_name').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Name');
	            }
	        });
	        
	        $('.agent_phone').focus(function(){
	            if($(this).val() == 'Phone') {
	                $(this).val('');
	            }
	        });

	        $('.agent_phone').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Phone');
	            }
	        });
	        
	        $('.agent_email').focus(function(){
	            if($(this).val() == 'Email') {
	                $(this).val('');
	            }
	        });

	        $('.agent_email').blur(function(){
	            if($(this).val() == '') {
	                $(this).val('Email');
	            }
	        });
		}	
	};


//Homeloan page
homloan_scrollToCalculator = {
	init: function() {
		var query = String(document.location).split('/');
	    var calculator = query[query.length-1];
	    if(calculator == 'calculator') {
	        $('html, body').animate({
	            scrollTop: $("#validate_field_types_home_loan_calculator").offset().top
	        }, 1000);
	        //});
	    }
	}
};

//Add your property
addYourProperty = {
	init: function() {
		$('#propertyfor_value').val($.trim($('#inputPropertyFor option:selected').text()));
		$('#inputPropertyFor').bind('change', function(){
			$('#propertyfor_value').val($.trim($('select[id="inputPropertyFor"] option:selected').text()));
			//$('#propertyfor_value').val($.trim($('#inputPropertyFor option:selected').text()));
		});
	
		$('#propertytype_value').val($.trim($('#inputPropertyType option:selected').text()));
		$('#inputPropertyType').bind('change', function(){
			$('#propertytype_value').val($.trim($('select[id="inputPropertyType"] option:selected').text()));
			//$('#propertyfor_value').val($.trim($('#inputPropertyFor option:selected').text()));
		});
	
		$('#city_value').val($.trim($('#city option:selected').text()));
		$('#city').bind('change', function(){
			$('#city_value').val($.trim($('select[id="city"] option:selected').text()));
		});
	
		$('#locality_value').val($.trim($('#sublocation option:selected').text()));
		$('#sublocation').bind('change', function(){
			$('#locality_value').val($.trim($('select[id="sublocation"] option:selected').text()));
		});
	
		$('#district_value').val($.trim($('#subarea option:selected').text()));
		$('#subarea').bind('change', function(){
			$('#district_value').val($.trim($('select[id="subarea"] option:selected').text()));
		});
		
		$('#priceunit_value').val($.trim($('#priceunit option:selected').text()));
		$('#priceunit').bind('change', function(){
			$('#priceunit_value').val($.trim($('select[id="priceunit"] option:selected').text()));
		});
	
		$('#tenure_value').val($.trim($('#tenure option:selected').text()));
		$('#tenure').bind('change', function(){
			$('#tenure_value').val($.trim($('select[id="tenure"] option:selected').text()));
		});
	}
};

//Login at the top right side on home page
memberRegistration = {
		init: function() {
			$('.btn-register').bind('click',function(){
				var url = siteurl + 'member/register';
				location = url;
			});
		}
};

//* scroll to top
scrollToTop = {
    init: function() {
        $('body').append('<a href="javascript:void(0)" class="scrollup" style="display:none"><i class="icon-chevron-up icon-white"></i></a>');
        
        $(window).scroll(function(){
            if ($(this).scrollTop() > 100) {
                $('.scrollup').fadeIn();
            } else {
                $('.scrollup').fadeOut();
            }
        });

        $('.scrollup').click(function(e){
            $("html, body").animate({ scrollTop: 0 }, 600);
            e.preventDefault();
        });
    }
};

scrollToHome = {
	    init: function() {
	        $('body').append('<a href="javascript:void(0)" class="to_home" style="display:none"><i class="icon-home"></i></a>');
	        
	        $(window).scroll(function(){
	            if ($(this).scrollTop() > 100) {
	                $('.to_home').fadeIn();
	            } else {
	                $('.to_home').fadeOut();
	            }
	        });

	        $('.to_home').click(function(e){
	        	var url = siteurl;
	        	location = url;
	        });
	    }
	};

contactUs = {
	    init: function() {
	        $('body').append('<a href="javascript:void(0)" class="contactUs" style="display:block"></a>');
	        
	        $('.contactUs').click(function(e){
	        	var url = siteurl + 'contact-us.html';
	        	location = url;
	        });
	    }
	};

//
$('select[name=\'city\']').bind('change', function() {
	//when city is not Bali
	if(this.value != 1) {
		$.ajax({
			url: siteurl + 'member/getListAllLocation?citiesVal=' + this.value,
			dataType: 'json',
			beforeSend: function() {
				$('select[name=\'city\']').after('<span class="wait">&nbsp;<img src="'+ siteurl +'assets/img/loading.gif" alt="" /></span>');
			},
			complete: function() {
				$('.wait').remove();
			},			
			success: function(json) {
				html = '<option value="">'+ text_all +'</option>';
				$.each(json, function(entryIndex, entry){
					if (entry['zone'] != '') {
						for (i = 0; i < entry['zone'].length; i++) {
							html += '<option value="' + entry['zone'][i]['Location_ID'] + '"';
							html += '>' + entry['zone'][i]['Name'] + '</option>';
						}
						$('#Add_Your_Property_Location').show();
						$('#Add_Your_Property_SubArea').show();
						$('select[name=\'sublocation\']').html(html);
						$('select[name=\'subarea\']').empty();
						$('select[name=\'subarea\']').html('<option value="">'+ text_all +'</option>');
					} else {
						$('#Add_Your_Property_Location').hide();
						$('#Add_Your_Property_SubArea').hide();
					}
				});
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	} else { //Bali is special case when it doesn't have any location, it just has sub area
		$.ajax({
			url: siteurl + 'member/getBaliSubArea?locationVal=' + this.value,
			dataType: 'json',
			beforeSend: function() {
				$('select[name=\'sublocation\']').after('<span class="wait">&nbsp;<img src="'+ siteurl +'assets/img/loading.gif" alt="" /></span>');
			},
			complete: function() {
				$('.wait').remove();
			},			
			success: function(json) {
				html = '<option value="">'+ text_all +'</option>';
				$.each(json, function(entryIndex, entry){
					if (entry['zone'] != '') {
						for (i = 0; i < entry['zone'].length; i++) {
							html += '<option value="' + entry['zone'][i]['Subarea_ID'] + '"';
							html += '>' + entry['zone'][i]['Name'] + '</option>';
						}
					}
				});
				//turn the location list box off first
				$('#Add_Your_Property_Location').hide();
				$('#Add_Your_Property_SubArea').show();
				$('select[name=\'subarea\']').html(html);
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
			}
		});
	}
}), $('select[name=\'sublocation\']').bind('change', function() {
	$.ajax({
		url: siteurl + 'member/getListAllSubArea?locationVal=' + this.value,
		dataType: 'json',
		beforeSend: function() {
			$('select[name=\'sublocation\']').after('<span class="wait">&nbsp;<img src="'+ siteurl +'assets/img/loading.gif" alt="" /></span>');
		},
		complete: function() {
			$('.wait').remove();
		},			
		success: function(json) {
			html = '<option value="">'+ text_all +'</option>';
			$.each(json, function(entryIndex, entry){
				if (entry['zone'] != '') {
					for (i = 0; i < entry['zone'].length; i++) {
						html += '<option value="' + entry['zone'][i]['Subarea_ID'] + '"';
						html += '>' + entry['zone'][i]['Name'] + '</option>';
					}
				}
			});
			
			$('select[name=\'subarea\']').html(html);
		},
		error: function(xhr, ajaxOptions, thrownError) {
			alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
		}
	});
});

//$('select[name=\'city\']').trigger('change');
//$('select[name=\'sublocation\']').trigger('change');

//toggle listing type in Refine Search
$('.property-filter input:radio[name=\'propertyfor\']').bind('change', function() {
	var propertyfor = $('.property-filter input:radio[name=propertyfor]:checked').val();
	if(propertyfor == "sale") {
		$('.property-filter .list_type').show();
	} else {
		$('.property-filter .list_type').hide();
	}
});

$('.property-filter input:radio[name=\'propertyfor\']').trigger('change');

function addToCart(product_id, quantity) {
    quantity = typeof(quantity) != 'undefined' ? quantity : 1;

    $.ajax({
        url: 'index.php?route=checkout/cart/add',
        type: 'post',
        data: 'product_id=' + product_id + '&quantity=' + quantity,
        dataType: 'json',
        success: function(json) {
            $('.success, .warning, .attention, .information, .error').remove();
			
            if (json['redirect']) {
                location = json['redirect'];
            }
			
            if (json['success']) {
                $('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
				
                $('.success').fadeIn('slow');
				
                $('#cart-total').html(json['total']);
				
                $('html, body').animate({
                    scrollTop: 0
                }, 'slow'); 
            }	
        }
    });
}
function addToWishList(listing_id) {
    var base_url = siteurl;
    $.ajax({
        url: base_url + 'shortlist/add',
        type: 'post',
        data: 'listingid=' + listing_id,
        dataType: 'json',
        success: function(json) {
            $('.success, .warning, .attention, .information').remove();
            if (json['success']) {            	
                //$('#notification').html('<div class="container"><div class="success alert alert-success" style="display: none;">' + json['success'] + '<img src="'+ base_url +'assets/img/close.png" alt="" class="close" /></div></div>');
				
                //$('.success').fadeIn('slow');
				
                $('#wishlist-total').html(json['total']);
				
//                $('html, body').animate({
//                    scrollTop: 0
//                }, 'slow');
            }
        }
    });
}

function addToCompare(product_id) { 
    $.ajax({
        url: 'index.php?route=product/compare/add',
        type: 'post',
        data: 'product_id=' + product_id,
        dataType: 'json',
        success: function(json) {
            $('.success, .warning, .attention, .information').remove();
						
            if (json['success']) {
                $('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
				
                $('.success').fadeIn('slow');
				
                $('#compare-total').html(json['total']);
				
                $('html, body').animate({
                    scrollTop: 0
                }, 'slow'); 
            }	
        }
    });
}

function viewResultListing(uri) {
    var base_url = siteurl;
    
    switch(uri) {
        case 'listing-grid':
            window.location = base_url + 'listing-rows.html';
            break;
        case 'listing-rows':
            window.location = base_url + 'listing-grid.html';
            break;
        default:
            window.location = base_url + 'listing-grid.html';
            break;
    }
}

function detailListing(id) {
    var base_url = siteurl;
    
    window.location = base_url + 'detail.html?id=' + id;
}

//contact agent - detail listing
$( ".button-contact-agent-detail-listing" ).submit(function( event ) {
	var name = $('input[name=\'name\']').attr('value');
	var phone = $('input[name=\'phone\']').attr('value');
	var email = $('input[name=\'email\']').attr('value');
	
	var bResult = true;
	
	if(name == "" || phone == "" || email == "") {
		bResult = false;
	}
	
	if(bResult) {
		$.ajax({
			url: siteurl + 'email/listingDetailContactAgent',
			type: 'post',
			data: $('#validate_field_contact_agent_detail_listing input[type=\'text\'], #validate_field_contact_agent_detail_listing textarea, #validate_field_contact_agent_detail_listing input[type=\'hidden\']'),
			dataType: 'json',
			beforeSend: function() {
				$('.modal-header').after('<span class="wait">&nbsp;<img src="'+ siteurl +'assets/img/loading.gif" alt="" /></span>');
			},
			complete: function() {
				$('.wait').remove();
			},			
			success: function(json) {
				$('#message_notification').html('<div class="success alert alert-success">' + json['success'] + '<img src="'+ siteurl +'assets/img/close.png" alt="" class="close" /></div>');
				$('input[name=\'name\']').val('');
				$('input[name=\'phone\']').val('');
				$('input[name=\'email\']').val('');
			}
		});
	}
	event.preventDefault();
});

//contact agent - result listing
$('.question_form').bind('click', function() {
	//var listing_ID  = $(this).parent().parent().children('#listing_id').val();
	var name   = $(this).parent().parent().find($('input[name=\'name\']')).val();
	var phone  = $(this).parent().parent().find($('input[name=\'phone\']')).val();
	var email  = $(this).parent().parent().find($('input[name=\'email\']')).val();
	
	var errMsg = '';
	if(name == "") {
		errMsg +='Please enter your name \n';
	}
	
	if(phone == "") {
		errMsg +='Please enter a valid phone number \n';
	}
	
	if(email == "") {
		errMsg +='Please enter a valid email address, such as name@domain.com \n';
	}
	
	if(errMsg != '') {
		alert(errMsg);
        return false;
    } else {
    	$.ajax({
			url: siteurl + 'email/listingDetailContactAgent',
			type: 'post',
			data: 'name='+ name +'&phone='+ phone +'&email='+ email +'', 
			dataType: 'json',
			beforeSend: function() {
				$('.modal-header').after('<span class="wait">&nbsp;<img src="'+ siteurl +'assets/img/loading.gif" alt="" /></span>');
			},
			complete: function() {
				$('.wait').remove();
			},			
			success: function(json) {
				$('#message_notification').html('<div class="success alert alert-success">' + json['success'] + '<img src="'+ siteurl +'assets/img/close.png" alt="" class="close" /></div>');
				$(this).parent().parent().find($('input[name=\'name\']')).val('');
				$(this).parent().parent().find($('input[name=\'phone\']')).val('');
				$(this).parent().parent().find($('input[name=\'email\']')).val('');
			}
		});
    }
});

//contact agent
$(".button-contact-agent-result-listing").submit(function(event){
	
	//var listing_ID  = $(this).parent().parent().children('#listing_id').val();
	var action = $(this).find($('input[name=\'action\']')).val();
	var name  = $(this).find($('input[name=\'name\']')).val();
	var phone = $(this).find($('input[name=\'phone\']')).val();
	var email = $(this).find($('input[name=\'email\']')).val();
	var listing_id = $(this).find($('input[name=\'listing_id\']')).val();
	var listing_name = $(this).find($('input[name=\'listing_name\']')).val();
	var datastring= $(this).closest('form').serialize();
	
	var errMsg = '';
	if(name == "") {
		errMsg +='Please enter your name \n';
	}
	
	if(phone == "") {
		errMsg +='Please enter a valid phone number \n';
	}
	
	if(email == "") {
		errMsg +='Please enter a valid email address, such as name@domain.com \n';
	}
	
	if(errMsg != '') {
		alert(errMsg);
        return false;
    } else {
    	$.ajax({
			url: siteurl + 'email/listingDetailContactAgent',
			type: 'post',
			//data: 'action='+ action +'&name='+ name +'&phone='+ phone +'&email='+ email +'&listing_id='+ listing_id +'&listing_name='+ listing_name,
			data: datastring,
			dataType: 'json',
			beforeSend: function() {
				$('.modal-header').after('<span class="wait">&nbsp;<img src="'+ siteurl +'assets/img/loading.gif" alt="" /></span>');
			},
			complete: function() {
				$('.wait').remove();
			},			
			success: function(json) {
				$('.message_notification').html('<div class="success alert alert-success">' + json['success'] + '<img src="'+ siteurl +'assets/img/close.png" alt="" class="close" /></div>');
				$('.button-contact-agent-result-listing').find($('input[name=\'name\']')).val('');
				$('.button-contact-agent-result-listing').find($('input[name=\'phone\']')).val('');
				$('.button-contact-agent-result-listing').find($('input[name=\'email\']')).val('');
			}
		});
    	event.preventDefault();
    }
});

//contact agent
$(".button-contact-agent-find-an-expert").submit(function(event){
	
	//var listing_ID  = $(this).parent().parent().children('#listing_id').val();
	var action = $(this).find($('input[name=\'action\']')).val();
	var name  = $(this).find($('input[name=\'name\']')).val();
	var phone = $(this).find($('input[name=\'phone\']')).val();
	var email = $(this).find($('input[name=\'email\']')).val();
	
	var errMsg = '';
	if(name == "") {
		errMsg +='Please enter your name \n';
	}
	
	if(phone == "") {
		errMsg +='Please enter a valid phone number \n';
	}
	
	if(email == "") {
		errMsg +='Please enter a valid email address, such as name@domain.com \n';
	}
	
	if(errMsg != '') {
		alert(errMsg);
        return false;
    } else {
    	$.ajax({
			url: siteurl + 'email/FindAnExpertContactForm',
			type: 'post',
			data: 'action='+ action +'&name='+ name +'&phone='+ phone +'&email='+ email, 
			dataType: 'json',
			beforeSend: function() {
				$('.modal-header').after('<span class="wait">&nbsp;<img src="'+ siteurl +'assets/img/loading.gif" alt="" /></span>');
			},
			complete: function() {
				$('.wait').remove();
			},			
			success: function(json) {
				$('.message_notification').html('<div class="success alert alert-success">' + json['success'] + '<img src="'+ siteurl +'assets/img/close.png" alt="" class="close" /></div>');
				$('.button-contact-agent-find-an-expert').find($('input[name=\'name\']')).val('');
				$('.button-contact-agent-find-an-expert').find($('input[name=\'phone\']')).val('');
				$('.button-contact-agent-find-an-expert').find($('input[name=\'email\']')).val('');
			}
		});
    	event.preventDefault();
    }
});

function contactAgent(id, type) {
    var base_url = siteurl;
    
    window.location = base_url + 'detail.html?id=' + id + '#contactAgent';
}

function searchByMap() {
    var base_url = siteurl;
    
    window.location = base_url + 'listing-map.html';
}

/*responsive youtube and vimeo videos*/
/*
(function() {
    var iframes = document.getElementsByTagName('iframe');
    
    for (var i = 0; i < iframes.length; i++) {
        var iframe = iframes[i];
        var players = /www.youtube.com|player.vimeo.com/;
        if(iframe.src.search(players) !== -1) {
            var videoRatio = (iframe.height / iframe.width) * 100;
            
            iframe.style.position = 'absolute';
            iframe.style.top = '0';
            iframe.style.left = '0';
            iframe.width = '100%';
            iframe.height = '100%';
            
            var div = document.createElement('div');
            div.className = 'video-wrap';
            div.style.width = '100%';
            div.style.position = 'relative';
            div.style.paddingTop = videoRatio + '%';
            
            var parentNode = iframe.parentNode;
            parentNode.insertBefore(div, iframe);
            div.appendChild(iframe);
        }
    }
})();
*/
/*End*/

var ww = document.body.clientWidth;

$(document).ready(function() {
    $(".nav2 li a").each(function() {
        if ($(this).next().length > 0) {
            $(this).addClass("parent");
        };
    })
	
    $(".toggleMenu").click(function(e) {
        e.preventDefault();
        $(this).toggleClass("active");
        $(".nav2").toggle();
    });
    adjustMenu();
})

$(window).bind('resize orientationchange', function() {
    ww = document.body.clientWidth;
    adjustMenu();
});

var adjustMenu = function() {
    if (ww < 768) {
        //$(".toggleMenu").css("display", "inline-block");
        if (!$(".toggleMenu").hasClass("active")) {
            $(".nav2").hide();
        } else {
            $(".nav2").show();
        }
        $(".nav2").show();
        $(".nav2 li").unbind('mouseenter mouseleave');
        $(".nav2 li a.parent").unbind('click').bind('click', function(e) {
            // must be attached to anchor element to prevent bubbling
            e.preventDefault();
            $(this).parent("li").toggleClass("hover");
        });
    } 
    else if (ww >= 768) {
        $(".toggleMenu").css("display", "none");
        $(".nav2").show();
        $(".nav2 li").removeClass("hover");
        $(".nav2 li a").unbind('click');
        $(".nav2 li").unbind('mouseenter mouseleave').bind('mouseenter mouseleave', function() {
            // must be attached to li so that mouseleave is not triggered when hover over submenu
            $(this).toggleClass('hover');
        });
    }
};

function sbRestArea(b,c,msg){
    $("input."+c+":checked").each(function(){
        this.checked=!1;
    });
    
    sbInitialArea(!0,c);
    $("."+b).html(msg);
}

function sbCheckUncheck(b,a,c,msg){
	$("#"+b).is(":checked")?$("input#"+b).each(function(){
		this.checked=!1;
	}):$("input#"+b).each(function(){
		this.checked=!0;
	});
	sbPopulateArea(a,c,msg);
}

function sbPopulateArea(b,c,msg){
	var a="",d=msg;
	var message = "";
	$("input."+c+":checked").each(function(){
		var message = $(this).parent().children('.sbChks').text();
		
		0==message.length?$(this).attr("checked",!1):a=a+","+message;
	});
	//0<a.length&&(d=a,30<a.length&&(d=a.substring(0,30)+"..."),0==a.indexOf(",")&&(a=a.substring(1),d=d.substring(1)));
	$("."+b).html(d);
	d==msg?sbInitialArea(!0,c):sbInitialArea(!1,c);
}

function sbInitialArea(b,c){
    $("input."+c+"").each(function(){
        0==$(this).val().length&&(this.checked=b?!0:!1);
    })
}

//Privacy and Term Of Use - Fancybox
$(function(){
	$(".privacystatement")
	    .attr('rel', 'gallery')
	    .fancybox({
	        type: 'iframe',
	        autoSize : false,
	        beforeLoad : function() {      
	            this.width  = parseInt(this.element.data('fancybox-width'));
	            this.height = parseInt(this.element.data('fancybox-height'));
	        }
	    });
	
	$(".termsofuse")
    .attr('rel', 'gallery')
    .fancybox({
        type: 'iframe',
        autoSize : false,
        beforeLoad : function() {         
            this.width  = parseInt(this.element.data('fancybox-width'));
            this.height = parseInt(this.element.data('fancybox-height'));
        }
    });
});

//Our Team - Fancybox
$(".opendetail").fancybox({
    'width'				: '75%',
    'height'			: 'auto',
    'titleShow'     : false,
    'transitionIn'	: 'elastic',
    'transitionOut'	: 'elastic',
    //'easingIn'      : 'easeOutBack',
    //'easingOut'     : 'easeInBack',
    'type'				: 'iframe'
});

//Our Team - Fancybox
$(".our-services-detail").fancybox({
	'maxWidth'	: '800',
	'maxHeight'	: '350',
	'fitToView'	: false,
	'width'		: '80%',
	'height'	: '18%',
    'titleShow'     : false,
    'transitionIn'	: 'elastic',
    'transitionOut'	: 'elastic',
    //'easingIn'      : 'easeOutBack',
    //'easingOut'     : 'easeInBack',
    'type'				: 'iframe'
});

function number_format (number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');
    // *    returns 13: '100 050.00'
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec);
        return '' + Math.round(n * k) / k;
    };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

//Loan Calculator
function ComputeLoan() {
	var s = validation();
	if (s != true)
		return;
	lar = deFormatCurrency(document.getElementById("txtLAR").value);
	ir = document.getElementById("txtIR").value;
	lt = document.getElementById("txtLT").value;
	mof = document.getElementById("txtMOF").value;
	if(mof == "Annual") {
		mof = 1;
	} else {
		mof = 1;
	}
	
	lat = lar * 1 * mof;
	// Calculate Monthly Repayment
	if (lt > 0) {
		mr = -pmt((ir / 100) / 12, (lt * 12), (lat), 0, 0);
	}
	else
	{
		mr = 0;
	}
	// Calculate Min. Monthly Income Required
	mmir = mr / (33 / 100);
	document.getElementById("txtLAR").value = formatCurrency(lar);
	document.getElementById("txtMR").value = formatCurrency(mr);
}
function pmt(rate, nper, pv, fv, p_type) {
	var pvif = Math.pow(1 + rate, nper);
	var fvifa = (Math.pow(1 + rate, nper) - 1) / rate;
	var type1 = (p_type != 0) ? 1 : 0;
	var lvamt = ((-pv * pvif - fv) / ((1 + rate * type1) * fvifa));
	if (isNaN((-pv * pvif - fv) / ((1 + rate * type1) * fvifa)))
		return 0.00;
	else
		return ((-pv * pvif - fv) / ((1 + rate * type1) * fvifa));
}
function deFormatCurrency(num) {
	num = num.toString().replace(/\$|\,/g, '');
	return num;
}
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g, '');
	if (isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num * 100 + 0.50000000001);
	cents = num % 100;
	num = Math.floor(num / 100).toString();
	for ( var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
		num = num.substring(0, num.length - (4 * i + 3)) + ','
				+ num.substring(num.length - (4 * i + 3));
	return (((sign) ? '' : '-') + num);
}
function IsNumeric(sText) {
	var ValidChars = "0123456789.,";
	var IsNum = true;
	var Char;
	for (i = 0; i < sText.length && IsNum == true; i++) {
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			IsNum = false;
		}
	}
	return IsNum;
}
function validation() {
	// Interest Rate
	if (!IsNumeric(document.getElementById("txtIR").value)) {
		alert("Please Enter Number Only.");
		$('#txtIR').focus();
		return false;
	}
	// Loan Tenure
	if (!IsNumeric(document.getElementById("txtLT").value)) {
		alert("Please Enter Number Only.");
		$('#txtLT').focus();
		return false;
	}
	return true;
}

/*Check (find) an item in Javascrip Array
 */
Array.prototype.has=function(v){
    for (i=0;i<this.length;i++){
       if (this[i] == v) 
           return true;
    }
    return false;
}